package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.WechatUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.FamilyElderDto;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.service.*;
import com.zzyl.serve.vo.FamilyElderPageVo;
import com.zzyl.serve.vo.FamilyElderVo;
import com.zzyl.serve.vo.MemberLoginVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-21
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IFamilyMemberElderService familyMemberElderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IDeviceService deviceService;


    private static final List<String> NICK_NAME_POOL = List.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        // 1. 向微信平台发请求获取openid
        String openid = wechatUtil.getOpenid(dto.getCode());
        // 2. 向微信平台发请求获取手机号
        String phone = wechatUtil.getPhone(dto.getPhoneCode());
        // 3. 根据微信账号openid，到数据库表里查询一下
        LambdaQueryWrapper<FamilyMember> wrapper = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);
        // 4. 判断是否查到家属信息了
        if (familyMember == null) {
            familyMember = new FamilyMember();
            // 给用户设置昵称，而不是使用了用户的微信昵称。昵称：从nickNamePool里随机取一个昵称，再拼接上手机号后4位
            familyMember.setName(NICK_NAME_POOL.get(new Random().nextInt(NICK_NAME_POOL.size())) + phone.substring(phone.length() - 4));
            familyMember.setOpenId(openid);
            familyMember.setPhone(phone);
            save(familyMember);
        } else {
            // 如果手机号 和 数据库里的手机号不同，则需要更新手机号
            if (!phone.equals(familyMember.getPhone())) {
                familyMember.setPhone(phone);
                updateById(familyMember);
            }
        }
        // 5. 准备返回值
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(familyMember.getName());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", familyMember.getId());
        claims.put("name", familyMember.getName());
        vo.setToken(tokenService.createToken(claims));
        return vo;
    }








    @Override
    public void bindFamily(FamilyElderDto dto) {
        //查询老人数据
        Elder elderData = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName())
                .eq(Elder::getStatus, 1)
                .select(Elder::getId)
                .one();
        //判断老人信息是否一致
        if (elderData == null) {return;}
        //获取当前用户Id（家属Id）
        Long familyId = UserThreadLocal.getUserId();
        //封装对象保存数据库
        FamilyMemberElder fmElder = new FamilyMemberElder();
        fmElder.setElderId(elderData.getId());
        fmElder.setFamilyMemberId(familyId);
        fmElder.setRemark(dto.getRemark());
        familyMemberElderService.save(fmElder);
    }

    @Override
    public List<FamilyElderPageVo> listByPage(Integer pageNum, Integer pageSize) {
        //获取当前用户Id（家属Id）
        Long familyId = UserThreadLocal.getUserId();
        //查询绑定家人关系表
        List<FamilyMemberElder> list = familyMemberElderService
                .lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, familyId)
                .list();
        //补充数据
        List<FamilyElderPageVo> resList = new ArrayList<>();
        for (FamilyMemberElder fmElder : list) {
            FamilyElderPageVo vo = new FamilyElderPageVo();
            //获取循环内当前老人数据
            Elder elderData = elderService.lambdaQuery()
                    .eq(Elder::getId, fmElder.getElderId())
                    .select(Elder::getName,Elder::getImage,Elder::getBedNumber)
                    .one();
            //获取当前老人入住房型名称
            Bed bedData = bedService.lambdaQuery()
                    .eq(Bed::getBedNumber, elderData.getBedNumber())
                    .select(Bed::getRoomId)
                    .one();
            Room roomData = roomService.lambdaQuery()
                    .eq(Room::getId, bedData.getRoomId())
                    .select(Room::getTypeName)
                    .one();
            //获得当前老人的设备信息
            Device deviceData = deviceService.lambdaQuery()
                    .eq(Device::getBindingLocation, fmElder.getElderId())
                    .eq(Device::getProductName,"智能定位报警手表")
                    .select(Device::getIotId, Device::getDeviceName, Device::getProductKey)
                    .one();
            //封装对象
            vo.setMid(fmElder.getId());
            vo.setMremark(fmElder.getRemark());
            vo.setElderId(fmElder.getElderId());
            vo.setName(elderData.getName());
            vo.setImage(elderData.getImage());
            vo.setBedNumber(elderData.getBedNumber());
            vo.setTypeName(roomData.getTypeName());
            vo.setIotId(deviceData.getIotId());
            vo.setDeviceName(deviceData.getDeviceName());
            vo.setProductKey(deviceData.getProductKey());
            resList.add(vo);
        }
        return resList;
    }

    @Override
    public List<FamilyElderVo> getFamilyList() {
        //获取当前用户Id（家属Id）
        Long familyId = UserThreadLocal.getUserId();
        //查询绑定家人关系表
        List<FamilyMemberElder> list = familyMemberElderService
                .lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, familyId)
                .list();
        //封装返回值
        List<FamilyElderVo> resList = new ArrayList<>();
        for (FamilyMemberElder fme : list) {
            FamilyElderVo vo = new FamilyElderVo();
            vo.setId(fme.getId());
            vo.setFamilyMemberId(fme.getFamilyMemberId());
            vo.setElderId(fme.getElderId());
            Elder elderData = elderService.lambdaQuery()
                    .eq(Elder::getId, vo.getElderId())
                    .select(Elder::getName, Elder::getImage, Elder::getBedNumber)
                    .one();
            vo.setElderName(elderData.getName());
            resList.add(vo);
        }

        return resList;
    }

    @Override
    public void deleteGetById(Long id) {
        familyMemberElderService.removeById(id);
    }

}
